<template>
  <div class="page-container">
    <div class="handoff">
      <div
        :class="{ selected: item.value == tagVal }"
        :key="item.value"
        v-for="item in tagList"
        @click="tagHandle(item)"
      >
        {{ item.label }}
      </div>
    </div>
    <div class="common-content-wrap" v-show="tagVal == 1">
      <TrTable
        v-model="routeSearchParams"
        isNeedSelection
        :btnList="routeList"
        :total="routeTotalNum"
        :searchShowList="routeSearchShowList"
        :tableColumn="routeTableColumn"
        :tableData="routeTableData"
        :minSearchLabelWidth="100"
        requestName="getFlowListHandle"
        ref="routeTable"
        @add="addHandle"
        @flowRemove="flowRemoveHandle"
        @export="exportHandle(1)"
        @flowEdit="operateHandle($event, 'flowEdit')"
        @copy="operateHandle($event, 'copy')"
        @enable="operateHandle($event, 'enable')"
        @stop="operateHandle($event, 'stop')"
        @flowDelete="operateHandle($event, 'flowDelete')"
      />
    </div>
    <div class="common-content-wrap" v-show="tagVal == 2">
      <TrTable
        v-model="routeSearchParams"
        isNeedSelection
        :btnList="productList"
        :total="proTotalNum"
        :minSearchLabelWidth="100"
        :searchShowList="productSearchShowList"
        :searchHideList="productSearchHideList"
        :tableColumn="productTableColumn"
        :tableData="productTableData"
        requestName="getProductListHandle"
        ref="productTable"
        @productAdd="productOpera('productAdd')"
        @productRemove="productOpera('productRemove')"
        @export="exportHandle(2)"
        @productDelete="operateHandle($event, 'productDelete')"
        @change-switch="changeSwitchHandle"
      />
    </div>
    <RouteFlow
      v-model="isShowRoutePopup"
      :workOrdTypeList="workOrdTypeList"
      :detailData="flowDetailData"
      :operaType="operaType"
      @confrim="confrimHandle"
    ></RouteFlow>
    <TrFormPopup
      v-model="isShowProductPopup"
      :width="480"
      title="关联产品"
      ref="trEdit"
      :valueObj.sync="productObj"
      :formData="productData"
      :list="productPopupList"
      :relationList="relationList"
      @close="isShowProductPopup = false"
      @confrim="confrimProductHandle"
    />
  </div>
</template>
<script>
import {
  getFlowList,
  getProductList,
  removeFlow,
  getFlowDetail,
  updateFlow,
  createProduct,
  removeProduct,
  updateProduct,
} from "@/api/baseCode/processRoute";
import { getColor } from "@/utils/billColor";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import RouteFlow from "./components/RouteFlow.vue";
import enumData from "@/utils/enumCode.js";
import TrFormPopup from "@/components/Tr-form/Tr-form-popup.vue";
export default {
  name: "processRouteBox",
  components: {
    TrTable,
    RouteFlow,
    TrFormPopup,
  },
  data: () => ({
    isShowRoutePopup: false,
    tagVal: 1,
    tagList: [
      { label: "工艺路线", value: 1 },
      { label: "关联产品", value: 2 },
    ],
    routeSearchParams: {
      current: 1,
      size: 10,
    },
    routeTotalNum: 0,
    routeList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "删除",
        option: "flowRemove",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    routeSearchShowList: [
      {
        id: "typeCode",
        label: "工艺线路类别",
        type: "select",
        width: 33.33,
        value: [],
        list: [],
      },
      {
        id: "craft",
        label: "工艺路线名称",
        type: "input",
        width: 33.33,
        value: "",
      },
    ],

    routeTableColumn: [
      {
        type: "text",
        label: "类别",
        value: "typeName",
      },
      {
        type: "text",
        label: "编码",
        value: "code",
      },
      {
        type: "text",
        label: "名称",
        value: "name",
      },
      {
        type: "text",
        label: "版本号",
        value: "version",
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "启用日期",
        value: "activeTime",
      },
      {
        type: "text",
        label: "失效日期",
        value: "expireTime",
      },
      {
        type: "text",
        label: "创建人",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "更新人",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "更新时间",
        value: "updateTime",
      },
      {
        type: "text",
        label: "描述",
        value: "remark",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 140,
        showBtnList: [
          {
            label: "编辑",
            option: "flowEdit",
          },
          {
            label: "复制",
            option: "copy",
          },
        ],
        hideBtnList: [
          {
            label: "启用",
            option: "enable",
          },
          {
            label: "停用",
            option: "stop",
          },
          {
            label: "删除",
            option: "flowDelete",
          },
        ],
      },
    ],
    routeTableData: [],
    productList: [
      {
        label: "新增",
        option: "productAdd",
        color: "blue",
      },
      // {
      //   label: "导入",
      //   option: "productImport",
      //   color: "white",
      // },
      {
        label: "删除",
        option: "productRemove",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    productSearchShowList: [
      {
        id: "craftRouteName",
        label: "工艺路线名称",
        type: "input",
        width: 33.33,
        value: "",
      },
      {
        label: "产品类别",
        type: "loadselect",
        width: 33.3,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/material-category/rpc-page",
          method: "post",
          searchKey: "categoryName",
          rlLabel: "categoryName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        value: "",
        id: "materialCategoryId",
      },
      {
        label: "产品",
        type: "loadselect",
        width: 33.3,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialName",
          rlLabel: "materialName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        value: "",
        id: "materialId",
      },
    ],
    productSearchHideList: [
      {
        label: "线体",
        type: "loadselect",
        width: 33.3,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/line/page",
          method: "post",
          searchKey: "lineName",
          rlLabel: "lineName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        value: "",
        id: "lineId",
      },
    ],
    productTableData: [],
    productTableColumn: [
      {
        type: "text",
        label: "工艺路线编码",
        value: "craftRouteCode",
      },
      {
        type: "text",
        label: "工艺路线名称",
        value: "craftRouteName",
      },
      {
        type: "text",
        label: "工艺路线版本号",
        value: "craftRouteVersion",
      },
      {
        type: "text",
        label: "产品类别编码",
        value: "materialCategoryCode",
      },
      {
        type: "text",
        label: "产品类别名称",
        value: "materialCategoryName",
      },
      {
        type: "text",
        label: "产品编码",
        value: "materialCode",
      },
      {
        type: "text",
        label: "产品名称",
        value: "materialName",
      },

      {
        type: "text",
        label: "线体编码",
        value: "lineCode",
      },
      {
        type: "text",
        label: "线体名称",
        value: "lineName",
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "switch",
        label: "是否默认",
        value: "defaultFlagStatus",
      },
      {
        type: "text",
        label: "创建人",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 80,
        showBtnList: [
          {
            label: "删除",
            option: "productDelete",
          },
        ],
      },
    ],
    proTotalNum: 0,
    workOrdTypeList: [],
    flowDetailData: {},
    operaType: "add",
    isShowProductPopup: false,
    productObj: {},
    productData: {},
    productPopupList: [
      // {
      //   label: "时间选择",
      //   type: "daterange",
      //   timeType: "date",
      //   width: 100,
      //   value: "",
      //   id: "timeResr",
      // },
      {
        label: "工艺路线",
        type: "loadselect",
        width: 100,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/craft-route/page",
          method: "post",
          searchKey: "craft",
          rlLabel: "name",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: { validVersion: 1 },
        value: "",
        id: "craftRouteId",
      },
      {
        label: "产品类别",
        type: "loadselect",
        width: 100,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/material-category/rpc-page",
          method: "post",
          searchKey: "categoryName",
          rlLabel: "categoryName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
        value: "",
        id: "materialTypeId",
        isNeed: false,
      },
      {
        label: "产品",
        type: "loadselect",
        width: 100,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialName",
          rlLabel: "materialName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
        value: "",
        id: "materialId",
        isNeed: false,
      },
      {
        label: "线体",
        type: "loadselect",
        width: 100,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/line/page",
          method: "post",
          searchKey: "lineName",
          rlLabel: "lineName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: { isEnabled: [1] },
        value: "",
        id: "lineId",
        isNeed: false,
      },
      {
        label: "状态",
        type: "radio",
        width: 100,
        value: 1,
        id: "state",
        list: [
          {
            label: "启用",
            value: 1,
          },
          {
            label: "停用",
            value: 0,
          },
        ],
      },
      {
        label: "默认",
        type: "radio",
        width: 100,
        value: 1,
        id: "defaultFlag",
        list: [
          {
            label: "是",
            value: 1,
          },
          {
            label: "否",
            value: 0,
          },
        ],
      },
    ],
    relationList: [
      {
        id: "materialId",
        relaList: [
          {
            disabled: false,
            relaId: "materialTypeId",
            relaValue: "materialCategoryId",
            relaLabel: "materialCategoryName",
            relaParamsKey: ["materialCategoryId"],
            params: [
              {
                labelWord: "categoryName",
                realWord: "rlLabel",
              },
            ],
          },
        ],
      },
      {
        id: "materialTypeId",
        relaList: [
          {
            relaId: "materialId",
            disabled: false,
            relaParamsKey: ["categoryName"],
            params: [
              {
                labelWord: "materialCategoryId",
                realWord: "rlValue",
              },
            ],
          },
        ],
      },
    ],
  }),
  computed: {
    ids() {
      let ids = [];
      this.$refs.routeTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    productIds() {
      let ids = [];
      this.$refs.productTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  methods: {
    exportHandle(code) {
      this.$exportHandle({ vm: this, params: this.routeSearchParams, code });
    },
    async changeSwitchHandle(val) {
      let flag = val.defaultFlag == 1 ? 0 : 1;
      let res = await updateProduct(val.id, flag);
      if (res.data.code != 200) return this.$message.error(res.data.msg);
      this.$message.success(this.$t("msg.success"));
      this.getProductListHandle();
    },
    operateHandle(val, type) {
      switch (type) {
        case "flowEdit":
        case "copy":
          this.operaType = type;
          this.getFlowDetailHandle(val.id);
          break;
        case "enable":
        case "stop": {
          let params = {
            id: val.id,
            state: type == "enable" ? 1 : 0,
          };
          let tip =
            type == "enable"
              ? this.$t("tip.enableTip")
              : this.$t("tip.unenableTip");
          this.updateFlowHandle(params, tip);
          break;
        }
        case "flowDelete":
          this.removeFlowHandle([val.id]);
          break;
        case "productDelete":
          this.removeProductHandle([val.id]);
          break;
      }
    },
    async getFlowDetailHandle(id) {
      let res = await getFlowDetail(id);
      if (res.data.code != 200) return this.$message.error(res.data.msg);
      this.flowDetailData = res.data.data;
      this.isShowRoutePopup = true;
    },
    flowRemoveHandle() {
      this.removeFlowHandle(this.ids);
    },
    updateFlowHandle(params, tip) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [tip],
      })
        .then(async () => {
          let res = await updateFlow(params);
          if (res.data.code != 200) return this.$message.error(res.data.msg);
          this.$message.success(this.$t("msg.success"));
          this.getFlowListHandle();
        })
        .catch(() => {});
    },
    removeFlowHandle(ids) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          let res = await removeFlow(ids);
          if (res.data.code != 200) return this.$message.error(res.data.msg);
          this.$message.success(this.$t("msg.success"));
          this.$refs.routeTable.clearSelect();
          this.getFlowListHandle();
        })
        .catch(() => {});
    },
    removeProductHandle(ids) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          let res = await removeProduct(ids);
          if (res.data.code != 200) return this.$message.error(res.data.msg);
          this.$message.success(this.$t("msg.success"));
          this.$refs.productTable.clearSelect();
          this.getProductListHandle();
        })
        .catch(() => {});
    },
    confrimHandle() {
      this.getFlowListHandle();
    },
    tagHandle(tagObj) {
      if (!tagObj.value == this.tagVal) return;
      this.tagVal = tagObj.value;
      if (tagObj.value == 1) {
        this.$refs.routeTable?.doLayout();
      } else if (tagObj.value == 2) {
        this.$refs.productTable?.doLayout();
      }
    },
    addHandle() {
      this.operaType = "add";
      this.flowDetailData = {};
      this.isShowRoutePopup = true;
    },
    getFlowListHandle() {
      getFlowList(this.routeSearchParams).then((res) => {
        if (res.data.code != 200) return this.$message.error(res.data.msg);
        let data = res.data.data;
        this.$validateData(data);
        this.routeTableData = data.records;
        this.routeTableData.forEach((item) => {
          item["stateNameColor"] = getColor("DF", item.state);
          item["isShowenable"] = item.state != 0;
          item["isShowstop"] = item.state != 1;
        });
        this.routeTotalNum = data.total;
      });
    },
    getProductListHandle() {
      getProductList(this.routeSearchParams).then((res) => {
        if (res.data.code != 200) return this.$message.error(res.data.msg);
        let data = res.data.data;
        this.$validateData(data);
        this.productTableData = data.records;
        this.productTableData.forEach((item) => {
          item["stateNameColor"] = getColor("QT", item.state);
          item.defaultFlagStatus = item.defaultFlag == 1;
        });
        this.proTotalNum = data.total;
      });
    },
    async initHandle() {
      const res = await this.$fetchEnumData([enumData.workOrderType]);
      const column = this.$findByProperty(
        this.routeSearchShowList,
        "id",
        "typeCode"
      );
      this.workOrdTypeList = res[enumData.workOrderType];
      this.$set(column, "list", res[enumData.workOrderType]);
    },
    async confrimProductHandle() {
      if (
        !this.productObj.lineId &&
        !this.productObj.materialId &&
        !this.productObj.materialTypeId
      )
        return this.$message.warning("产品类别，产品，线体至少选择一个!");
      let res = await createProduct(this.productObj);
      if (res.data.code != 200) return this.$message.error(res.data.msg);
      this.$message.success(this.$t("msg.success"));
      this.isShowProductPopup = false;
      this.getProductListHandle();
    },
    productOpera(type) {
      if (type == "productAdd") return (this.isShowProductPopup = true);
      this.removeProductHandle(this.productIds);
    },
  },
  mounted() {
    // this.getFlowListHandle();
    // this.getProductListHandle();
    this.initHandle();
  },
};
</script>
